package com.jiawa.train.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.CommonResp;
import com.jiawa.train.common.util.JwtUtil;
import com.jiawa.train.member.domain.po.Member;
import com.jiawa.train.member.mapper.MemberMapper;
import com.jiawa.train.member.req.MemberLoginReq;
import com.jiawa.train.member.resp.MemberLoginResp;
import com.jiawa.train.member.service.IMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

;

/**
 * <p>
 * 会员 服务实现类
 * </p>
 *
 * @author hrz
 * @since 2025-09-06
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {


    @Override
    public CommonResp<Long> register(String mobile) {
        Member one = this.lambdaQuery().eq(Member::getMobile, mobile).one();
        if(one!=null){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_EXIST);
        }
        Member member = new Member();
        member.setMobile(mobile);
        baseMapper.insert(member);
        return new CommonResp<>(member.getId());
    }

    @Override
    public void sendCode(String mobile) {
        List<Member> list = this.lambdaQuery()
                .eq(Member::getMobile, mobile)
                .list();
        if(CollUtil.isEmpty(list)){
            //手机号不存在
            //1.保存到数据库
            Member member = new Member();
            member.setMobile(mobile);
            baseMapper.insert(member);
        }else{
            //手机号存在
            log.info("【手机号已存在】mobile={}",mobile);
        }
        //2.生成验证码
        String string = "8888";
        log.info("【发送验证码】mobile={},code={}",mobile,string);
        //3.保存短信记录表 id 手机号 验证码 有效期 是否使用 业务类型 发送时间 使用时间
        //4.发送短信
    }

    @Override
    public MemberLoginResp login(MemberLoginReq req) {
        List<Member> list = this.lambdaQuery()
                .eq(Member::getMobile, req.getMobile())
                .list();
        if(CollUtil.isEmpty(list)){
            //手机号不存在
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_NOT_EXIST);
        }
        //校验短信验证码
        if(!"8888".equals(req.getCode())){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_CODE_ERROR);
        }
        //登陆成功返回信息
        Member member = list.get(0);
        log.info("【登陆成功】member={}",member);
        MemberLoginResp memberLoginResp = new MemberLoginResp();
        /*拷贝属性*/
        BeanUtil.copyProperties(member,memberLoginResp);
        //生成jwt令牌 - 放入属性中
        String token = JwtUtil.createToken(member.getId(), member.getMobile());
        memberLoginResp.setToken(token);
        return memberLoginResp;
    }
}
